package com.itheima.service.Impl;

import com.itheima.entity.ShoppingCart;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 作用：添加购物车
     *
     * @param shoppingCart 当前提交的购物项的数据
     * @return
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //1. 根据用户的id与dish_id 或者setmeal_id查看购物车表是否存在该购物项
        ShoppingCart shoppingCartnew = shoppingCartMapper.findUidAndDidAndSid(shoppingCart);
        //如果没找到就添加进去
        if (shoppingCartnew == null) {
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartMapper.save(shoppingCart);
            shoppingCartnew = shoppingCart;
        } else {
            //如果已经存在，则数量加一
            shoppingCartnew.setNumber(shoppingCartnew.getNumber() + 1);
            shoppingCartMapper.update(shoppingCartnew);
        }
        return shoppingCartnew;

    }

    @Override
    public List<ShoppingCart> list(long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.fincartByUserId(userId);
        return shoppingCartList;
    }

    @Override
    public void delete(long userid) {
        shoppingCartMapper.delete(userid);

    }

    @Override
    public ShoppingCart deleteByDishidOrSetmealid(ShoppingCart shoppingCart) {
        //得到用户购物车的数据
        ShoppingCart shoppingCart2=   shoppingCartMapper.findSCByUserId(shoppingCart);

//        ShoppingCart shoppingCart1 = shoppingCartMapper.findBySCId(shoppingCart);
      //得到购物车数量
//        int count=  shoppingCartMapper.findShoppingCartNumber(shoppingCart2);

        if (shoppingCart2.getNumber() >0){
            shoppingCart2.setNumber(shoppingCart2.getNumber()-1);
            shoppingCartMapper.updateByNumber(shoppingCart2);
//            ShoppingCart shoppingCart2 = shoppingCartMapper.findBySCId(shoppingCart);
//            ShoppingCart shoppingCart3=   shoppingCartMapper.findSCByUserId(shoppingCart2);
//            return shoppingCart2;
        }
        if (shoppingCart2.getNumber() ==0){
            shoppingCartMapper.deleteByDishidOrSetmealid(shoppingCart2);
//            return shoppingCart2;
        }
        //判断是否读于1，是的话number-1
//        if (shoppingCart2.getNumber() == 0) {
////            shoppingCartMapper.deleteByDishidOrSetmealid(shoppingCart2);
//
//        }
        return shoppingCart2;
    }
}
